import { createRouter, createWebHistory } from 'vue-router'
import unified from './unified';
import { getCookie } from "@/utils/cookie.js"
import { useAuthStore } from '@/stores/modules/auth.js';
import { ElMessage } from 'element-plus'

const routes = [
  /**后台管理 */
  {
    path: '/',
    name: 'root',
    /* redirect: '/AppManager/Index', */
    component: () => import('@/components/layout/FrontLayout.vue'),
    children: unified
  },
  {
    path: '/Home/Login',
    name: 'login',
    meta: { title: '登录' },
    component: () => import('@/views/login/login.vue'),
  },
  {
    path: '/Home/empower',
    name: 'empower',
    meta: { title: '授权' },
    component: () => import('@/views/login/empower.vue'),
  },
  {
    path: '/Home/Logout',
    name: 'Logout',
    meta: { title: '退出' },
    component: () => import('@/views/login/logout.vue'),
  },
  {
    path: '/Home/resgiter',
    name: 'resgiter',
    meta: { title: '注册' },
    component: () => import('@/views/login/resgiter.vue'),
  },
  {
    path: '/Error',
    name: 'Error',
    meta: { hidden: true, title: '错误' },
    component: () => import('@/views/system/Error.vue')
  },
  /* { path: '/:pathMatch(.*)*', name: 'NotMatch', redirect: '/', meta: { hidden: true } } */
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

/* 白名单 */
const whiteList = ['/', '/Home/Login', '/Home/empower', '/Home/Logout', '/Home/resgiter', '/Error']

router.beforeEach((to, from, next) => {

  if (whiteList.includes(to.path)) {
    document.title = to.meta.title
    return next()
  }

  let url = ""
  if(to.fullPath.indexOf("?") > -1) {
    url = to.fullPath.slice(to.fullPath.indexOf("?"))
  }

  /* 无cookie跳转登录 */
  if(!getCookie("base_auth_user")){
    if(url) {
      return window.open(router.resolve(`/Home/Login${url}`).href, "_self")
    } else {
      return window.open(router.resolve(`/Home/Login?return_url=${to.path}`).href, "_self")
    }
  }

  /* 处理权限 */
  const authStore = useAuthStore()
  const actionTree = authStore?.base_auth_tree || []
  const routeActions = actionTree.find(item => item.controlName == "left_menu")

  /* 没有左侧菜单栏的权限信息，未登录 */
  if(!routeActions || routeActions.length) {
    const is = () => {
      ElMessage({
        type: 'warning',
        message: "您暂未获得统一认证系统的权限，无法进入该页面！请尝试重新登录，或联系管理员进行配置！",
        showClose: true,
        duration: 3000,
        onClose: () => {
          window.open("/Home/Login", "_self")
        }
      })
    }
    return is()
  }

  /* 所有有权限的左侧菜单 */
  const allRouteActions = routeActions.children.filter(item => item.selected == 1)

  /* 判断要进入的路由是否有权限 */
  if (allRouteActions && allRouteActions.length) {
    if (!allRouteActions.find(item => item.controlName == to.path && item.selected == 1)) {
      const is = () => {
        ElMessage({
          type: 'warning',
          message: "暂未获取对应模块权限，无法进入该界面！",
          showClose: true,
          duration: 2000,
          onClose: () => {
            window.open(from.path, "_self")
          }
        })
      }
      return is()
    }
  } else {
    const is = () => {
      ElMessage({
        type: 'warning',
        message: "您暂未获得统一认证系统的权限，无法进入该页面！请尝试重新登录，或联系管理员进行配置！",
        showClose: true,
        duration: 3000,
        onClose: () => {
          window.open("/Home/Login", "_self")
        }
      })
    }
    return is()
  }

  /* 设置web标题 */
  document.title = to?.meta?.title
    ? `${to.meta.title} | ${import.meta.env.VITE_APP_WEB_TITLE}`
    : import.meta.env.VITE_APP_WEB_TITLE

  next()
})

export const SetupRouter = {
  install: (app) => {
    app.use(router)
  }
}

export default router
